<template>
<div class="info">
  <section class="qq box" @contextmenu.prevent @click="toggleRight(false)">
    <section class="top bg">
      <i class="el-icon-arrow-left"></i>
      <span>问答机器人 (beta)</span>
      <i class="el-icon-info"></i>
    </section>
    <section class="center">
      <section class="task">
        <section class="msg" v-for="(msg,index) in msgArr" :key="index" :class="{r: msg.k}">
          <div><img :src="msg.img" alt="头像"></div>
          <div class="text" @mousedown="showRight($event,index)" v-if="!msg.audio">{{msg.text}}</div>
          <div v-else class="audio">
            <div class="text mp3" @click="playAudio(msg.index, index)" @mousedown="showRight($event,index)">
              <i class="iconfont icon-yuyin" :class="{pp : playIndex === index}"></i>
            </div>
            <span class="time">{{msg.text}}"</span>
          </div>
        </section>
      </section>
    </section>
    <el-input v-model="uInput" class="bottom" @keyup.enter.native="setI(uInput)">
      <el-button slot="append" icon="el-icon-upload2" @click="setI(uInput)"></el-button>
      <el-button slot="prepend" @click="jAudio">
        <i class="iconfont" :class="[status ? 'icon-luzhi ss' : 'icon-yuyin1']"></i>
      </el-button>
    </el-input>
  </section>
  <section>
    <div id="hide-play" style="display: none"></div>
  </section>
  <div class="right-show" @contextmenu.prevent :style="right.style">
    <span v-for="item in right.data" @click="rightClick(item.text)" :key="item.text">{{item.text}}</span>
  </div>
</div>
</template>
<script>
import { upAudio } from '../api/getData2'
import Record from '../assets/js/recording'
import { getSmart } from '../api/getData'

export default {
  name: 'mp3',
  data: function () {
    return {
      playIndex: null,
      right: {
        data: [{text: '播放'},{text: '翻译'}],
        style: {
          display: 'none'
        },
        now: null
      },
      rec: '',
      status: false,
      audio: {
        index: 0
      },
      str: '',
      uInput: '',
      msgArr: [
        {
          img: require('../assets/1.jpg'),
          text: '你好,我是无所不知得小助手,点击左侧语音按钮和我语音对话哦'
        }
      ]
    }
  },
  created: function () {
    // this.$router.replace('/edit')
  }, // 创建时
  beforeMount: function () {}, // 挂载之前
  mounted: function () {
    this.initAudio()
    this.getAudio(this.msgArr[0].text)
  }, // 挂载之后
  beforeUpdate: function () {}, // 数据更新时调用,在渲染之前
  updated: function () {}, // 数据更新后,渲染后调用(禁止)
  beforeDestroy: function () {}, // 实例销毁前调用,解绑中间层的数据传输
  destroyed: function () {}, // 实例销毁后调用
  methods: {
    rightClick (type) {
      let i = this.right.now
      console.log('--i--', i, type)
      if (type === '转语音') {
        this.getAudio(this.msgArr[i].text)
      }
    },
    toggleRight (b) {
      if (b) {} else {
        this.right.style = {
          display: 'none'
        }
      }
    },
    showRight (e,i) {
      // console.log('--e,i --', e,i )
      this.right.now = i
      let temp = e.target.className.split(" ")
      let type = temp.includes('mp3')
      if (e.button !== 2) {
        return false
      }
      if (type) {
        /* 语音 */
        this.right.data = []
      } else {
        this.right.data = [{text: '转语音'},{text: '更多'}]
      }
      this.right.style = {
        display: 'flex',
        position: 'absolute',
        left: e.x + 'px',
        top: e.y +'px'
      }
    },
    initAudio () {
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia
      if (navigator.getUserMedia) {
        navigator.getUserMedia({audio: true}, (stream) => {
          console.log('--授权--')
          this.rec = new Record({stream: stream})
        }, () => {
          console.log('--失败--')
        })
      }
    },
    startAudio () {
      this.rec.startRecorder()
    },
    stopAudio () {
      /* 本地预览 */
      this.getAudio(URL.createObjectURL(this.rec.getBlob()), true)
      /* 识别 */
      // this.rec.sendpcm(this.rec.getBlob())
      upAudio(this.rec.getBlob()).then(res => {
        console.log('--audio--', res)
        this.setI(res.data, false)
      })
      this.rec.clearRecorder()
      this.rec.stopRecorder()
    },
    setI (text, k = true) {
      if (k) {
        this.uInput = ''
        if (!text.trim().length) { return false }
      }
      /* 显示消息 */
      this.msgArr.push({
        k,
        img: require(k ? '../assets/2.jpg' : '../assets/1.jpg'),
        text
      })
      /* 滚动底部 */
      this.$nextTick(() => {
        document.querySelector('.center').scrollTop = document.querySelector('.msg:nth-last-of-type(1)').offsetTop
      })
    },
    jAudio () {
      console.log('--this.status--', this.status)
      !this.status ? this.startAudio() : this.stopAudio()
      this.status = !this.status
    },
    getAudio (text, k = false) {
      let src = k ? text : 'https://192.168.100.57:88/bdvoice/tts?txt=' + text
      let audio = document.createElement('audio')
      audio.src = src
      audio.controls = true
      document.getElementById('hide-play').append(audio)
      /* 获取时长 */
      audio.addEventListener('loadedmetadata', () => {
        console.log('--audio.duration--', audio.duration)
        console.log('--加载完成--')
        console.log('--k--', k)
        this.msgArr.push({
          k,
          img: require(k ? '../assets/2.jpg' : '../assets/1.jpg'),
          index: this.audio.index,
          audio: true,
          text: Math.ceil(audio.duration === Infinity ? 60 : audio.duration)
        })
        /* 滚动底部 */
        this.$nextTick(() => {
          document.querySelector('.msg-box').scrollTop = document.querySelector('.msg:nth-last-of-type(1)').offsetTop
        })
        this.audio.index += 1
      })
      audio.addEventListener('ended', () => {
        this.playIndex = null
        console.log('--播放完毕--')
        console.log('--audio.duration--', audio.duration)
      })
      audio.addEventListener('play', () => {
        console.log('--开始播放--')
        console.log('--audio.duration--', audio.duration)
      })
    },
    playAudio (i,index) {
      this.playIndex = index
      document.querySelectorAll('#hide-play audio').forEach(v => {
        v.pause()
      })
      let audio = document.querySelectorAll('#hide-play audio')[i]
      audio.play()
    },
    setAudio () {

    }
  } // 函数
}
</script>
<style lang='scss'>
@function getPX($n) {
  @return $n * 0.5px;
}

.right-show {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 70px;
  text-align: center;
  background-color: white;
  box-shadow: #5a5a6b 0 0 2px;
  z-index: 9;
  span {
    display: block;
    width: 100%;
    height: 30px;
    line-height: 30px;
    &:hover {
      background-color: deepskyblue;
    }
  }
}
.pp {
  animation: myfirst 0.6s infinite ease alternate;
  transition: all 1s;
}
.ss {
  animation: ssgg 1.2s infinite ease alternate;
  transition: all 1s;
  display: inline-block;
  color: red;
  font-size: 40px;
}

@keyframes ssgg {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(1.5);
  }
}

@keyframes myfirst {
  from {
    font-size: 12px;
    color: #b5b3b3;
  }
  to {
    font-size: 16px;
    color: #b5b4ba;
  }
}

.info {

  box-sizing: border-box;
  line-height: normal;
  .qq {
    height: getPX(1280);
    width: getPX(750);
    box-shadow: 0 0 6px 1px #282828;
  }
  .box {
    display: flex;
    flex-direction: column;
    .top {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      i {
        padding: getPX(40);
      }
      &.bg {
        background-color: #3a393e;
        color: #fff;
        height: getPX(82)
      }
    }
    .center {
      flex: 1;
      overflow-y: scroll;
      background-color: #ebebeb;
      &::-webkit-scrollbar {
        width: 0;
      }
      .task {
        display: flex;
        flex-direction: column;
        padding: getPX(20);
        .msg {
          display: flex;
          flex-direction: row;
          align-items: center;
          margin-top: getPX(26);
          .audio {
            display: flex;
            flex-direction: row;
            align-items: flex-end;
            .text {
              min-width: 40px;
              max-height: 24px;
            }
          }
          .time {
            margin-left: 10px;
            color: #aba4a4;
            font-size: 14px;
            line-height: 32px;
          }
          .text {
            background-color: #fff;
            padding: getPX(22);
            border-radius: getPX(14);
            position: relative;
            margin-left: 10px;
            text-align: left;
            word-wrap: break-word;
            max-width: 280px;
            &::before {
              content: "";
              height: 0px;
              width: 0px;
              position: absolute;
              left: -17px;
              top: 50%;
              margin-top: -9.5px;
              z-index: 0;
              border-left: 9px solid transparent;
              border-top: 9px solid transparent;
              border-bottom: 9px solid transparent;
              border-right: 9px solid rgba(63, 63, 63, 0.1);
            }
            &::after {
              content: "";
              height: 0px;
              width: 0px;
              position: absolute;
              left: -17px;
              top: 50%;
              margin-top: -9.5px;
              z-index: 1;
              border-left: 9px solid transparent;
              border-top: 9px solid transparent;
              border-bottom: 9px solid transparent;
              border-right: 9px solid rgb(255, 255, 255);
            }
          }
          &.r {
            justify-content: flex-end;
            .audio {
              order: -1;
              .text {
                text-align: right;
                i {
                  transform: rotate(180deg);
                  display: inline-block;
                }
              }
              .time {
                order: -3;
                margin-left: 0;
                margin-right: 10px;
              }
            }
            .text {
              order: -1;
              background-color: #a0e759;
              margin-left: 0;
              margin-right: 10px;
              &::before {
                left: auto;
                right: -17px;
                border-left: 9px solid #a0e759;
                border-right: 9px solid transparent;
              }
              &::after {
                left: auto;
                right: -17px;
                border-right: 9px solid transparent;
                border-left: 9px solid #a0e759;
              }
            }
          }
          img {
            width: getPX(84);
            height: getPX(84);
          }
        }
      }
    }
    .bottom {
      height: getPX(97);
      input {
        height: 100%;
        font-size: 20px;
        outline: none;
      }
    }
  }
}
</style>
